package com.smh.demo1.a11;

import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author shiminghui
 * @date 2025/4/16 16:56
 * @description: TODO
 */
public class Proxy extends Target {
    static Method read;

    static MethodProxy readMethodProxy;

    static {
        try {
            read = Target.class.getMethod("read", int.class);
            // 参数解释 目标类, 代理类,参数类型,目标方法名,代理方法名
            readMethodProxy = MethodProxy.create(Target.class, Proxy.class, "(I)V", "read", "readSuper");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    private MethodInterceptor methodInterceptor;

    public Proxy(MethodInterceptor methodInterceptor) {
        this.methodInterceptor = methodInterceptor;
    }

    public void readSuper(int sum) {
        System.out.println("没有使用反射,使用的是父类的方法");
        super.read(sum);
    }

    @Override
    public void read(int sum) {

        try {
            methodInterceptor.intercept(this, read, new Object[]{sum}, readMethodProxy);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
